package com.luoye.lj.platform.controller;

import com.luoye.lj.platform.controller.log.RoleAddGenerator;
import com.luoye.lj.platform.controller.log.RoleDeleteGenerator;
import com.luoye.lj.platform.controller.log.RoleModifyGenerator;
import com.luoye.lj.platform.model.domain.*;
import com.luoye.lj.platform.model.enums.RoleType;
import com.luoye.lj.platform.service.IAuthService;
import com.luoye.lj.platform.service.IMuserservice;
import com.luoye.lj.platform.service.IRoleService;
import com.luoye.lj.util.mvc.annotation.OperateLog;
import com.luoye.lj.util.mvc.data.SimpleListResult;
import com.luoye.lj.util.mvc.data.SimpleResponseBody;
import com.luoye.lj.util.mvc.util.PageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Dave Liu
 * Date: 15-11-8
 * Time: 下午7:50
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/system/role")
public class RoleController {
    protected static final Logger logger = LoggerFactory.getLogger(RoleController.class.getSimpleName());

    @Autowired
    private IMuserservice muserservice;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IAuthService authService;

    @RequestMapping("/list")
    public String list(Model model) {
        model.addAttribute("title","角色管理");
        List<RoleType> roleTypeList=RoleType.getAll();
        model.addAttribute("roleTypeList",roleTypeList);
        return "system/role/role_list";
    }

    @RequestMapping("/search")
    @ResponseBody
    public SimpleListResult search(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "max", defaultValue = "10") int max, HttpServletRequest request, Model model, RoleInfoSearch condition){
        SimpleListResult slr=new SimpleListResult();
        int offset = (page - 1) * max;
        logger.debug("offset->" + offset + ",max->" + max);
        SearchParams searchParams = new SearchParams();
        searchParams.setOffset(offset);
        searchParams.setMax(max);
        condition.setSearch(searchParams);
        try {
            RoleCollection roleCollection= roleService.search(condition);
            slr.setRows(roleCollection.getRoles());
            slr.setCurrentPage(page);
            slr.setResults(roleCollection.getTotalCount());
            slr.setPages(PageService.countPages(max, slr.getResults()));
            logger.debug("roleCollection = " + roleCollection);
        }catch (Exception ex){
            logger.warn(""+ex.getMessage(),ex);
        }
        return slr;
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    @OperateLog(value = "系统级别的角色添加",descriptionGenerator = RoleAddGenerator.class)
    public SimpleResponseBody add(String authstr, HttpServletRequest request, RoleSaveInfo roleSaveInfo){
        List<AuthInfo> auths = new ArrayList<AuthInfo>();
        if(!StringUtils.isEmpty(authstr)){
            String[] authidArray = authstr.split("#");
            for (String id : authidArray) {
                AuthInfo authInfo = new AuthInfo();
                authInfo.setId(Long.parseLong(id));
                auths.add(authInfo);
            }
        }
        roleSaveInfo.setAuths(auths);
        SimpleResponseBody<RoleInfo> srb=new SimpleResponseBody<RoleInfo>();
        try {
            srb.setOk(roleService.addRole(roleSaveInfo));
        }catch (Exception ex){
            logger.warn(""+ex.getMessage(),ex);
            srb.setOk(false);
            srb.setMsg("发生了未知错误");
        }
        return srb;
    }

    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    @ResponseBody
    @OperateLog(value = "系统级别的角色修改",descriptionGenerator = RoleModifyGenerator.class)
    public SimpleResponseBody modify(String authstr,HttpServletRequest request,RoleSaveInfo roleSaveInfo) {
        List<AuthInfo> auths = new ArrayList<AuthInfo>();
        String[] authidArray = authstr.split("#");
        for (String id : authidArray) {
            AuthInfo authInfo = new AuthInfo();
            authInfo.setId(Integer.parseInt(id));
            auths.add(authInfo);
        }
        roleSaveInfo.setAuths(auths);
        SimpleResponseBody<RoleInfo> srb = new SimpleResponseBody<RoleInfo>();
        try {
            boolean isOk = roleService.modifyRole(roleSaveInfo);
            srb.setOk(isOk);
        } catch (Exception ex) {
            logger.warn("" + ex.getMessage(),ex);
            srb.setOk(false);
            srb.setMsg("发生了未知错误");
        }
        return srb;
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ResponseBody
    @OperateLog(value = "系统级别的角色删除",descriptionGenerator = RoleDeleteGenerator.class)
    public SimpleResponseBody delete(HttpServletRequest request,long roleId){
        SimpleResponseBody<RoleInfo> srb=new SimpleResponseBody<RoleInfo>();
        try {
            boolean isOk = roleService.delRole(roleId);
            srb.setOk(isOk);
        }catch (Exception ex){
            logger.warn(""+ex.getMessage(),ex);
            srb.setOk(false);
            srb.setMsg("发生了未知错误");
        }
        return srb;
    }

    @RequestMapping("/authList")
    public String authsList(){return "system/role/auth_list";}

    @RequestMapping("/authSearch")
    @ResponseBody
    public SimpleListResult authSearch(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "max", defaultValue = "10") int max, AuthInfoSearchCondition authInfo) {
        int offset = (page - 1) * max;
        AuthInfoDetailCollection authInfoDetailCollection = new AuthInfoDetailCollection();
        authInfo.getSearchParams().setOffset(offset);
        authInfo.getSearchParams().setMax(max);
        try {
            authInfoDetailCollection = authService.search(authInfo);
        } catch (Exception e) {
            logger.warn(e.getMessage(),e);
        }
        SimpleListResult slr = new SimpleListResult();
        slr.setResults(authInfoDetailCollection.getTotalCount());
        slr.setRows(authInfoDetailCollection.getDetailList());
        slr.setCurrentPage(page);
        slr.setPages(PageService.countPages(max, authInfoDetailCollection.getTotalCount()));
        return slr;
    }

}
